const DataMgr = require('ym-Data');
let AcTimer = [0, 1000];
// var _ids = ['5c2eeb5d489b871ce4763142']
// var tokens = ['0']

// var _ids = ['5c70181bf236281b1b2a01c9'] //易炼
// var tokens = ['FFxoiiUBaJfwbk0f51VeOg==']

var _ids = ['5c6e8949f48049033a023e91']
var tokens = ['iayAtolmN559D9RaN82dJQ==']

var b_gameResIsLoad = false

cc.Class({
    extends: require('UI-PanelWindow'),

    properties: {
        monsterCfg : cc.JsonAsset,
        btnSpecial1 : require('SpriteAnimate'),
        btnSpecial2 : require('SpriteAnimate'),
        Toast:cc.Prefab,
        alert :cc.Prefab
    },

    onLoad: function () {
        var tbase_skillhero = require('base_skillhero')
        var heroskill = new tbase_skillhero()
        for(var key in heroskill){
            var v = heroskill[key]
            global.SkillConfig['hero/'+key] = v;
        }

        var tbase_skillboss = require('base_skillboss')
        var bossskill = new tbase_skillboss()
        for(var key in bossskill){
            var v = bossskill[key]
            global.SkillConfig['boss/'+key] = v;
        }

        var tbase_skill = require('base_skillmaster')
        var skill = new tbase_skill()
        Object.assign(global.SkillConfig,new tbase_skill())

        global.Loader.addPrefab('Eject/Toast',this.Toast);
        global.Loader.addPrefab('Eject/Alert',this.alert);

        // for(var key in this.skillbossCfg.json){
        //     var v = this.skillbossCfg.json[key]
        //     global.SkillConfig['boss/'+key] = v;
        // }
        // for(var key in this.skillmasterCfg.json){
        //     var v = this.skillmasterCfg.json[key]
        //     global.SkillConfig[key] = v;
        // }
        // global.PathConfig = this.pathCfg.json
        // global.ParticleConfig = this.particleCfg.json;
        var tbase_path = require('base_path')
        global.PathConfig = new tbase_path();
        var tbase_oarticle = require('base_particle')
        global.ParticleConfig = new tbase_oarticle()
        var rc = require('RewardComponent');
        let has = rc.hasVideo()
        global.DataConfig.monster = this.monsterCfg.json
    },


    start: function () {
        this.showPanel = null;

        this.weChatLogin()
        // var wei_id = cc.sys.localStorage.getItem('wei_id');
        // var token = cc.sys.localStorage.getItem('weitoken');
        // var openid = cc.sys.localStorage.getItem('weiopenid');
        // if(!!wei_id && !!token && !!openid){
        //     this.toLogin(null,{_id:wei_id,token:token,openid:openid})
        // } else if(CC_WECHATGAME){
        //     this.addPlane();
        //     wx.RankKey = 'score',
        //     wx.LevelKey = 'level'
        //     // this.node.getChildByName('guest').active = false;
        //     global.Platform.login(this.weChatLogin.bind(this));
        // } else {
        //     this.addPlane();
        //     global.Common.addButtonHandler(this,cc.find('view/startGame',this.node),'onLogin',0)
        // }
        // this.btnEffectFirst = true;
        // this.playButtonEffect();
    },

    weChatLogin(){
        var wei_id = cc.sys.localStorage.getItem('wei_id');
        var token = cc.sys.localStorage.getItem('weitoken');
        var openid = cc.sys.localStorage.getItem('weiopenid');
        var wei_code = cc.sys.localStorage.getItem('wei_code');
        if(!!wei_id && !!token && !!openid){
            this.toLogin(null,{_id:wei_id,token:token,openid:openid})
        } else if(CC_WECHATGAME){
            // this.node.getChildByName('guest').active = false;
            global.Platform.login(this.onWeChatLogin.bind(this));
        } else {
            this.onLogin(null,0);
        }
    },

    addPlane(){
        if(this.showPanel){
            return;
        }
        var self=this
        cc.loader.loadRes('main/center',cc.Prefab,function(err,res){
            if(!err){
                var node = cc.instantiate(res);
                self.node.addChild(node)
                node.x=0;
                node.y=-50
                self.showPanel = node
            }
        })
        this.showPlane()
    },

    showPlane(){
        let ress = [];
        for(var name in global.DataConfig.monster){
            var monster = global.DataConfig.monster[name];
            for(var skey in monster.status){
                let actions = monster.status[skey];
                for(let i=0; i<actions.length; i++){
                    if(!!actions[i].prefab){
                        ress.push(actions[i].prefab);
                    }
                    if(!!actions[i].bulletTeam){
                        ress.push(actions[i].bulletTeam);
                    }
                }
            }
        }
        cc.loader.loadResArray(ress,function(err,result){
            if(err){
                return
            }
            for(var i=0; i<result.length; i++){
                let name = result[i].name
                var full = ress.find(item=>{return item.indexOf(name) >=0})
                global.Loader.addPrefab(full,result[i])
            }
        })
    },


    playButtonEffect(){
        var self = this;
        if(this.btnEffectFirst){
            this.btnSpecial1.node.active = true;
            this.btnSpecial1.startAnimate(1,function(){
                self.btnSpecial1.node.active =false;
            })
            this.btnSpecial2.node.active = false;
        } else {
            this.btnSpecial2.node.active = true;
            this.btnSpecial2.startAnimate(1,function(){
                self.btnSpecial2.node.active =false;
            })
            this.btnSpecial1.node.active = false;
        }
        this.btnEffectFirst = !this.btnEffectFirst
        this.scheduleOnce(this.playButtonEffect.bind(this),0.8+Math.random()*0.5)
    },

    cleanResource(){
        global.Platform.cleanResource()
    },

    onWeChatLogin: function (data) {
        cc.log('weChatLogin:',data);
        var query = global.Platform.getLaunchOption()
        var option2 = global.Platform.getReferrerInfo();
        console.log('query:',query);
        if(query &&!!query.parentId){
            data.parentId = query.parentId
        }
        if (option2) {
            data.referrerInfoAppId = query.channel;
            if (!data.referrerInfoAppId && option2.extraData && option2.extraData.channel) data.referrerInfoAppId = option2.extraData.channel;
        }
        CC_WECHATGAME&&wx.hideLoading()
        if(data.code){
            CC_WECHATGAME && wx.showShareMenu()
            CC_WECHATGAME&&wx.showLoading({title:'登陆中',mask:true})
            this.httpGet('/game/gameUser/codeLogin', '', data, this.toLogin.bind(this));
        } else {
            var wei_id = cc.sys.localStorage.getItem('wei_id');
            var openid = cc.sys.localStorage.getItem('weiopenid');
            var token = cc.sys.localStorage.getItem('weitoken');
            this.toLogin(null,{_id:wei_id,token:token,openid:openid})
        }
    },

    onLogin: function (event,data) {
        
        SoundMgr.playButtonEffect()
        var idx = parseInt(data);
        var d = {_id:_ids[idx],token:tokens[idx]};
        
        this.toLogin(null,d)
    },

    toLogin(err,data){
        console.log('weChatLogin:',data);
        global.Platform.destroyLoginButton()

        if(err){
            CC_WECHATGAME&&wx.hideLoading()
            global.Platform.login(this.onWeChatLogin.bind(this));
            return;
        }
        
        global.Data._id = data._id
        global.Data.token = data.token
        global.Data.openid = data.openid
        global.Http.setOptions({_id:global.Data._id,token:global.Data.token})
        const Http = require('ym-Http')
        Http.setOptions({_id:global.Data._id,token:global.Data.token})
        cc.sys.localStorage.setItem('weitoken',data.token);
        cc.sys.localStorage.setItem('wei_id',data._id);

        

        var self = this;

        this.httpGet('/game/gameUser','checkLogin',{}, function(err,res){
            console.log('res:',res)
            CC_WECHATGAME&&wx.hideLoading()
            if(err){
                let eject = global.EJMgr.pushUI('Eject/Alert');
                eject.getComponent('Alert').setOptions({title:'提示',message:'缓存有错，需要重新登陆',autoClose:false,ok:function(){
                    if(CC_WECHATGAME){
                        global.Platform.cleanResource(function(){
                            cc.game.restart();
                        })
                    } else {
                        cc.sys.localStorage.clear();
                        cc.game.restart();
                    }
                }})
                return
            }
            Object.assign(global.Data,res);
            self.loginOK(err,global.Data);
        });
    },
    onDestroy(){
    },
    loginOK: function (err,data) {
        cc.log('======>>登录成功!', data,global.DataConfig);
        cc.sys.localStorage.setItem('weiopenid',data.openid);
        cc.sys.localStorage.setItem('weitoken',data.token);
        DataMgr.setData('loginData',global.Data);
        const Http = require('ym-Http')
        Http.setOptions({_id:global.Data._id,token:global.Data.token})
        CC_WECHATGAME&&wx.postMessage({
            messageType : 6,
            openType : wx.LevelKey,
            plotId :global.Data.currentPass
        })
        this._toLoadMainSceneResource(function(){
            global.UIMgr.clearNode();
            global.BannerAD.init();
            global.UIMgr.loadLayer('SelectPlane',0)
        })
        global.Data.isNewUser = global.Common.calcDetailDay(new Date(data.registerTimeTick),new Date()) == 0;
        console.log('global.Data.isNewUser:',global.Data.isNewUser)
        // global.
        //判断新用户
            
        // global.UIMgr.popUI();
        // global.Loader.loadResources('GameLoop',function(err,res){
        //     global.GameLoop.startLoop();
        // })

        if(CC_WECHATGAME){
            wx.postMessage({
                messageType : -1,
                openId : global.Data.openid
            })
        }
    },

    _toLoadMainSceneResource(finishCB){
        if(b_gameResIsLoad){
            finishCB()
            return
        }
        var loadding=cc.find('Canvas/Loadding');
        let progre = cc.find('UI-ProgressBar', loadding)
        loadding.active = true;
        progre.js.setPercent(0);
        // let consolelabel = loadding.getComponent('console').getComponent(cc.Label)
        var self = this;
        var async = new CCAsync();
        async.waterfall([
        function(cb){
            let ress = [];
            for(var name in global.DataConfig.monster){
                var monster = global.DataConfig.monster[name];
                for(var skey in monster.status){
                    let actions = monster.status[skey];
                    for(let i=0; i<actions.length; i++){
                        if(!!actions[i].prefab){
                            ress.push(actions[i].prefab);
                        }
                    }
                }
            }
            cc.loader.loadResArray(ress,function(err,result){
                if(err){
                    cb(err,0)
                    return
                }
                for(var i=0; i<result.length; i++){
                    let name = result[i].name
                    var full = ress.find(item=>{return item.indexOf(name) >=0})
                    global.Loader.addPrefab(full,result[i])
                }
                cb(err,result)
            })
        },
        function(d,cb){
            cc.loader.loadResDir('game/bullet',cc.AudioClip,function(p,a){
                progre.js.setPercent(p/a * 0.2+0.7);
            },function(err,res){
                cb(err,res)
                progre.js.setPercent(0.9);
            })
        },
        function(d,cb){
            let urls = global.Resources['SelectPlane']
            cc.loader.loadResArray(urls, (OKCount, sumCount) => {
                progre.js.setPercent(0.9+OKCount / sumCount*0.1);
            }, (error, assets) => {
                if (!error) {
                    for (let i = 0; i < assets.length; i++) {
                        global.Loader.addPrefab(urls[i],assets[i])
                    }
                }
                cb(error,assets)
            });
        },
        function(err,res){
            if(err){
                console.log('主界面资源加载失败，正在重新加载:',err)
                self._toLoadMainSceneResource(finishCB)
                return;
            }
            loadding.active = false
            b_gameResIsLoad = true;
            finishCB();
        }])
    },

    

    // update (dt) {},
});
